class MUtil {
  request(param){
    return new Promise((resolve,reject)=>{
      $.ajax({
        type:param.type || 'get',
        url:param.url || '',
        dataType: param.dataType || 'json',
        data: param.data || null,
        success: res =>{
          if(0 === res.status){
            //数据请求成功
            typeof resolve === 'function' && resolve(res.data , res.msg)
          }else if(10 ===res.status){
            //做登录
            this.doLogin();
          }else{
            typeof reject === 'function' && reject(res.msg || res.data)
          }
        },
        error: err =>{
          console.log(err)
          typeof reject === 'function' && reject(err.statusText)

        }
      })
    })

  }
  //跳转登录
  doLogin(){
    window.location.href = '/login?redirect=' + encodeURIComponent(window.location.pathname);
  }
  //获取url参数
  getUrlParam(name){
    //param=123&param1=456
    let queryString = window.location.search.split('?')[1] || '';
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    let result = queryString.match(reg);// result: ['param=123','','123','&']
    return result ? decodeURIComponent(result[2]) : null;
  }
  //错误提示
  errorTips(errMsg){
    alert(errMsg || '好像哪里不对了')
  }
  //设置本地存储
  setStorage(key,value){
    let valueType = typeof value;
    if(valueType === 'object'){
      window.localStorage.setItem(key,JSON.stringify(value))
    }
    //基础类型
    else if(['number','string','boolean'].indexOf(valueType) >= 0){
      window.localStorage.setItem(key,value)
    }
    //其他类型（不支持）
    else{
      alert('该类型不能用于本地存储')
    }
  }
  //获取本地存储
  getStorage(key){
    let value = window.localStorage.getItem(key)
    if(value){
      return JSON.parse(value)
    }else{
      return ''
    }
  }
  //删除本地存储
  removeStorage(key){
    window.localStorage.removeItem(key)
  }
}
export default MUtil;